/*
 *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
 *  <p>
 *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 * https://www.gnu.org/licenses/lgpl.html
 *  <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibase4j.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ibase4j.jwt.utils.GeneratorUtils;
import org.ibase4j.jwt.utils.ZipUtils;
import org.ibase4j.system.mapper.SysGeneratorMapper;
import org.ibase4j.system.model.entity.GenConfig;
import org.ibase4j.system.service.SysGeneratorService;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author lengleng
 * @date 2019/2/1
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysGeneratorServiceImpl implements SysGeneratorService {
	private final SysGeneratorMapper sysGeneratorMapper;


	/**
	 * 分页查询表
	 *
	 * @param tableName 查询条件
	 * @return
	 */
	@Override
	public IPage<List<Map<String, Object>>> queryPage(Page page, String tableName) {
		return sysGeneratorMapper.queryList(page,tableName);
	}

	/**
	 * 生成代码
	 *
	 * @param genConfig 生成配置
	 * @return
	 */
	@Override
	public byte[] generatorCode(GenConfig genConfig) {
		String ganeTempPath = "D:\\work\\workspace\\iBase4J\\zCode";
		String ganerateOputPath = ganeTempPath + File.separator + GeneratorUtils.DIRNAME;
		GeneratorUtils.ganerate(ganeTempPath,genConfig);

//		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//		ZipOutputStream zip = new ZipOutputStream(outputStream);
//		ZipUtils.zipFiles(ganerateOputPath,ganeTempPath + "\\code.zip");
		log.debug("==========================开始下载生成的代码==========================");
		return ZipUtils.zipFiles(ganerateOputPath);
		//生成代码
//		GenUtils.generatorCode(genConfig, table, columns, zip);
//		IOUtils.close(zip);
//		return outputStream.toByteArray();
	}

	private Map<String, String> queryTable(String tableName) {
		return sysGeneratorMapper.queryTable(tableName);
	}

	private List<Map<String, String>> queryColumns(String tableName) {
		return sysGeneratorMapper.queryColumns(tableName);
	}
}
